package com.xuecheng.auth.controller;

import com.xuecheng.user.model.po.XcUser;
import com.xuecheng.user.service.WxAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Slf4j
@Controller
public class WxLoginController {

    private final WxAuthService wxAuthService;

    @Autowired
    public WxLoginController(WxAuthService wxAuthService) {
        this.wxAuthService = wxAuthService;
    }

    /**
     * 微信扫码回调
     *
     * @param code 授权码
     * @param state 扫码授权时传入的state
     * @return 重定向到登录页面，发起并组装登录请求
     */
    @RequestMapping("/wxLogin")
    public String wxLogin(String code, String state) {
        log.debug("微信扫码回调,code:{},state:{}", code, state);
        // 1. 请求微信申请令牌，拿到令牌查询用户信息，将用户信息写入本项目数据库
        XcUser xcUser = wxAuthService.wxAuth(code);
        // 2. 重定向到登录页面，发起并组装登录请求，只取出用户名即可，登录的过程其实微信已经合法校验了
        if (xcUser == null) return "redirect:http://www.51xuecheng.cn/error.html";
        String username = xcUser.getUsername();
        return "redirect:http://www.51xuecheng.cn/sign.html?username=" + username + "&authType=wx";
    }
}
